package com.service;

import com.dao.OrderDao;
import com.dao.StockDao;
import com.entity.Order;
import com.vo.StockVO;
import com.vo.req.OrderRequest;
import com.vo.req.Request;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;

import java.util.HashMap;
import java.util.List;

@Service

public class OrderServiceImpl implements OrderService{

    @Autowired
    OrderDao orderDao;

    @Autowired
    StockDao stockDao;

    @Override
    @Transactional(propagation=Propagation.REQUIRED,rollbackFor = Exception.class)
    public boolean save(@RequestBody OrderRequest orderRequest) throws Exception {
        List<Request> requests = orderRequest.getOrder();
        HashMap<String,Integer> map = new HashMap<>();
        int len = requests.size();
        int index = 0;
        //合并相同getGoodsId请求
        for(int i=0;i<len;i++){
            Request request = requests.get(i);
            if(map.containsKey(request.getGoodsId())){
                Request nowRequest = requests.get(map.get(request.getGoodsId()));
                nowRequest.setNumber(request.getNumber()+nowRequest.getNumber());
            }
            else{
                requests.set(index,request);
                map.put(request.getGoodsId(),index);
                index++;
            }
        }
        for(int i=index;i<len;i++){
            requests.remove(i);
        }
        //更改order表和stock表数据
        for (Request request : requests) {
            StockVO stockVO = stockDao.queryById(request.getGoodsId());
            if(stockVO !=null){
                int rest = stockVO.getNumber();
                //如果剩下不够预约，回滚
                if(rest< request.getNumber()) throw new Exception();
                stockDao.updateStock(request);
                Order order = orderDao.queryById(request.getGoodsId());
                if(order!=null){
                    request.setNumber(order.getNumber()+request.getNumber());
                    orderDao.updateOrder(request);
                }else{
                    orderDao.save(request);
                }
            }
        }
        return true;
    }
}
